package redis

import (
	"fmt"
	"time"
	"web_app/models"

	"github.com/go-redis/redis"

	"go.uber.org/zap"
)

// GetPostListByOrder 根据排序类型获取id列表
func GetPostListByOrder(p *models.ParamsPostInOrder) (ids []string, err error) {
	key := getRedisKey(KeyPostTimeZSet)
	if p.Order == models.OrderScore {
		key = getRedisKey(KeyPostScoreZSet)
	}
	//获取一个缓存key（根据社区分组）60s过期
	key = GetCacheKey(key, p.CommunityID)
	start := (p.PageSize - 1) * p.PageCount
	end := start + p.PageCount - 1
	ids, err = rdb.ZRevRange(key, start, end).Result()
	fmt.Println("Order:", p.Order, "=====ids:", ids)
	if err != nil {
		zap.L().Error("GetPostListByOrder failed", zap.Error(err))
		return
	}
	return
}

// GetPostVoteData 查询帖子的投票数
func GetPostVoteData(ids []string) ([]int64, error) {
	data := make([]int64, 0, len(ids))
	pipeline := rdb.Pipeline()
	for _, id := range ids {
		pipeline.ZCount(getRedisKey(keyPostVotedZSetPF+id), "1", "1")
	}
	cmders, err := pipeline.Exec()
	if err != nil {
		return nil, err
	}
	for _, cmder := range cmders {
		v := cmder.(*redis.IntCmd).Val()
		data = append(data, v)
	}
	return data, nil
}

// GetCacheKey 组合缓存Key（根据社区分组）60s过期
func GetCacheKey(OrderKey string, communityID string) string {
	//没有哦communityID直接返回原来的key不做分组处理
	if communityID == "" {
		return OrderKey
	}
	//社区key
	communityKey := getRedisKey(KeyCommunityPF + communityID)
	//拼接缓存key
	cacheKey := OrderKey + communityID
	if rdb.Exists(cacheKey).Val() < 1 {
		Pipeline := rdb.Pipeline()
		Pipeline.ZInterStore(cacheKey, redis.ZStore{
			Aggregate: "MAX",
		}, communityKey, OrderKey)
		Pipeline.Expire(cacheKey, 60*time.Second)
		_, err := Pipeline.Exec()
		if err != nil {
			zap.L().Error("getRedisKey failed", zap.Error(err))
			return OrderKey
		}
	}
	return cacheKey
}
